package com.TeacherInfoServer.listener;

import com.TeacherInfoServer.converter.TitleLevelConverter;
import com.TeacherInfoServer.converter.WhetherConverter;
import com.TeacherInfoServer.pojo.entity.Teacher;
import com.TeacherInfoServer.exception.JobNumberNotExistException;
import com.TeacherInfoServer.exception.RecordRepeatedException;
import com.TeacherInfoServer.pojo.entity.TitleHistory;
import com.TeacherInfoServer.pojo.excelImport.TitleHistoryExcel;
import com.TeacherInfoServer.common.service.TeacherService;
import com.TeacherInfoServer.common.service.TitleHistoryService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Data
@Slf4j
@Component
public class TitleHistoryListener implements ReadListener<TitleHistoryExcel> {
    @Autowired
    private TitleHistoryService titleHistoryService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private Validator validator;
    @Autowired
    private TitleLevelConverter titleLevelConverter;
    @Autowired
    private WhetherConverter whetherConverter;
    private final List<TitleHistory> titleHistoryList = new ArrayList<>();
    private final List<TitleHistory> updateList = new ArrayList<>();
    private final List<TitleHistory> addList = new ArrayList<>();
    private final Set<TitleHistoryExcel> titleHistoryFormSet = new HashSet<>();
    private Integer record;
    @Override
    public void invoke(TitleHistoryExcel titleHistoryExcel, AnalysisContext analysisContext) {
        Set<ConstraintViolation<TitleHistoryExcel>> violations = validator.validate(titleHistoryExcel);
        if (violations.isEmpty()){
            if (!titleHistoryFormSet.contains(titleHistoryExcel)){
                LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
                Teacher teacher = teacherService.getOne(wrapper.eq(Teacher::getTeacherId,titleHistoryExcel.getTeacherId()));
                if (teacher != null && teacher.getTeacherName().equals(titleHistoryExcel.getTeacherName())){
                    String isCurrentTitle;
                    if (titleLevelConverter.convertToExcelData(teacher.getJobTitleId()).equals(titleHistoryExcel.getTitleLevel())){
                        isCurrentTitle = "是";
                    } else {
                        isCurrentTitle = "否";
                    }
                    TitleHistory titleHistory =
                            new TitleHistory(null,
                                    titleHistoryExcel.getTeacherId(),
                                    titleLevelConverter.convertToJavaData(titleHistoryExcel.getTitleLevel()),
                                    titleHistoryExcel.getObtainDate(),
                                    whetherConverter.convertToJavaData(isCurrentTitle),1,null);
                    titleHistoryList.add(titleHistory);
                    titleHistoryFormSet.add(titleHistoryExcel);
                } else {
                    if (teacher == null) {
                        throw new JobNumberNotExistException();
                    } else {
                        throw new RuntimeException("工号与教师名不匹配：" + teacher.getTeacherId());
                    }
                }
            } else {
                throw new RecordRepeatedException();
            }
        } else {
            String errorMessage = violations.iterator().next().getMessage();
            throw new ConstraintViolationException(errorMessage, violations);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        List<TitleHistory> titleHistorys = titleHistoryService.list();
        titleHistoryList.forEach(titleHistory -> {
            Optional<TitleHistory> dbTitleHistoryOptional = titleHistorys.stream()
                    .peek(dbTitleHistory -> dbTitleHistory.setId(null))
                    .filter(titleHistory::equals)
                    .findFirst();
            dbTitleHistoryOptional.ifPresent(dbTitleHistory -> log.info("记录已存在数据库:{}",dbTitleHistory));
            if (dbTitleHistoryOptional.isEmpty()) {
                addList.add(titleHistory);
            }
        });
        List<TitleHistory> mergedList = Stream.concat(updateList.stream(), addList.stream())
                .collect(Collectors.toList());
        titleHistoryService.saveOrUpdateBatch(mergedList);
        setRecord(mergedList.size());
        initList();
    }

    public void initList(){
        titleHistoryList.clear();
        updateList.clear();
        addList.clear();
        titleHistoryFormSet.clear();
    }
}
